package cn.lili.listener;

import cn.hutool.json.JSONUtil;
import cn.lili.event.PaymentCallbackEvent;
import cn.lili.modules.payment.entity.dto.PaymentCallback;
import cn.lili.routing.PaymentRoutingKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 支付通知
 *
 * @author paulG
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PaymentMessageListener {

    /**
     * 支付事件
     */
    private final List<PaymentCallbackEvent> paymentCallbackEvents;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = ("${lili.amqp.payment}" + "_" + PaymentRoutingKey.PAYMENT_CALLBACK)),
            exchange = @Exchange(value = "${lili.amqp.payment}"),
            key = PaymentRoutingKey.PAYMENT_CALLBACK))
    public void onMessage(PaymentCallback paymentCallback) {
        log.info("支付成功mq消息");
        for (PaymentCallbackEvent paymentCallbackEvent : paymentCallbackEvents) {
            try {
                if (paymentCallbackEvent.getScene().equals(paymentCallback.getScene())) {
                    paymentCallbackEvent.paymentCallback(paymentCallback);
                }
            } catch (Exception e) {
                log.error("支付消息消费异常：在{}业务中,{},",
                        JSONUtil.toJsonStr(paymentCallback),
                        paymentCallbackEvent.getClass().getName(),
                        e);
            }
        }

    }


}
